package com.heima.search.Service.impl;

import com.heima.common.dtos.ResponseResult;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.model.search.pojos.ApAssociateWords;
import com.heima.search.Service.ApAssociateWordsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;


import java.util.List;

@Service
public class ApAssociateWordsServiceImpl implements ApAssociateWordsService {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Override
    public ResponseResult<List<ApAssociateWords>> search(UserSearchDto dto) {
        if(dto.getPageSize()==0)dto.setPageSize(10);

        Query query = Query.query(Criteria.where("associateWords").regex("^"+dto.getSearchWords()+".*"));
        query.with(Sort.by(Sort.Direction.DESC,"createdTime"));
        query.limit(dto.getPageSize());

        List<ApAssociateWords> wordsList = mongoTemplate.find(query, ApAssociateWords.class);

        return ResponseResult.okResult(wordsList);
    }
}
